/*
 * @Author: silence silence9685@163.com
 * @Date: 2023-06-13 15:44:38
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-01-04 10:40:45
 * @FilePath: \ems_neutral_app\lib\pages\Home\HomePage.dart
 * @Description: 首页
 */

import 'package:ems_neutral_app/bloc/userbloc/user_bloc.dart';
import 'package:ems_neutral_app/common/interfaceInstance/SmartRefresherInterfaceInstance.dart';
import 'package:ems_neutral_app/entities/UserEntity.dart';
import 'package:ems_neutral_app/pages/Home/Controller/AppManagerController.dart';
import 'package:ems_neutral_app/pages/Home/View/HomeSystermStateView.dart';
import 'package:ems_neutral_app/utils/color/ColorUtils.dart';
import 'package:ems_neutral_app/utils/eventBus/eventBus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sil_base_widget_package/sil_base_widget_package.dart';

import '../../../base/SilScaffold.dart';
import '../../api/request/PowerStationRequest.dart';
import '../../main.dart';
import '../../utils/string/StringConstant.dart';
import '../Mine/Language/SilLocalizations/SilLocalizations.dart';
import '../PowerStation/Controller/PowerStationController.dart';
import 'View/HomeDeviceBaseInfoView.dart';
import 'View/HomeTempMonitoringView.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();

  static Route route() {
    return MaterialPageRoute<void>(
      builder: (_) => HomePage(),
      settings: RouteSettings(name: '/HomePage'),
    );
  }
}

class _HomePageState extends State<HomePage>
    with RouteAware, SmartRefresherInterfaceInstance {
  PowerStationController _powerStationController =
      Get.put(PowerStationController());
  AppManagerController _appManagerController = Get.put(AppManagerController());

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    PageRoute route = ModalRoute.of(context) as PageRoute;
    route.settings.name;
    routeObserver.subscribe(this, ModalRoute.of(context) as PageRoute);
  }

  @override
  void dispose() {
    super.dispose();
    routeObserver.unsubscribe(this);
  }

  @override
  void didPopNext() {
    final route = ModalRoute.of(context)?.settings.name;
    print('返回到当前页面 A-didPopNext route: $route');

    /// 获取设备数据
    // initData();
  }

  @override
  void didPushNext() {
    final route = ModalRoute.of(context)?.settings.name;
    print('从当前页面跳到其他页面 route: $route');
  }

  @override
  void didPop() {
    final route = ModalRoute.of(context)?.settings.name;
    print('当前页面关闭 A-didPop route: $route');
  }

  @override
  void initState() {
    super.initState();

    /// 选择的设备发生了改变
    bus.on(StringConstant.SelectDeviceChange, (arg) {
      initData();
    });

    /// tabbar回到首页
    bus.on(StringConstant.APPGotoTabbar, (index) {
      if (index == 0) initData();
    });

    /// 绑定推送设备id，因为没有做多设备登录，每次都打开都需要绑定一次
    _appManagerController.bindPushCid();
  }

  /// 获取设备数据
  initData({bool showLoading = true}) {
    if (!this.mounted) return;

    /// 当前选中的电站信息
    UserEntity? userEntity = UserBlocTool.userEntity;
    _powerStationController.powerStationDetail(
      context: context,
      deviceId: userEntity?.powerRecordId,
      successHandler: (p0) {},
      showLoading: showLoading,
    );

    /// 我的电站列表
    _powerStationController.getPowerStationList(context);
  }

  @override
  Widget build(BuildContext context) {
    return SilScaffold(
      sideMargin: 0,
      navBarHide: true,
      backgroundColor: Colors.black,
      body: SilSmartRefresherWidget(
          isShowFooterNoData: false,
          enablePullUp: false,
          childBuild: (context, data) {
            return mainWidget();
          },
          loadDataFuture: ({manuallyRefresh, page}) {
            initData(showLoading: false);
            UserEntity? userEntity = UserBlocTool.userEntity;
            return api_power_station_info(
                deviceId: userEntity?.powerRecordId ?? "",
                throwException: true);
          },
          interface: this),
    );
  }

  mainWidget() {
    return CustomScrollView(
      slivers: [
        /// 电站基础信息
        SliverToBoxAdapter(child: HomeDeviceBaseInfoView()),

        /// 高压机型 显示温度监控
        SliverToBoxAdapter(child: TempMonitoringView()),

        /// 系统状态
        SliverToBoxAdapter(child: HomeSystermStateView()),

        /// 提示
        SliverToBoxAdapter(child: bottomPromptView())
      ],
    );
  }

  /// 温度监控(高压机型)
  TempMonitoringView() {
    return Obx(
      () {
        bool flag = false;

        /// 如果是思道尔机型，显示温度监控
        if (_powerStationController.powerStationEntity.value.stationType ==
            '3') {
          flag = true;
        } else {
          flag = _powerStationController
                  .powerStationEntity.value.equipmentSelection ==
              '1';
        }

        Widget tempWidget = flag ? HomeTempMonitoringView() : Container();
        return tempWidget;
      },
    );
  }

  bottomPromptView() {
    return Container(
      margin: EdgeInsets.only(top: 10.w, bottom: 40.w, left: 20.w, right: 20.w),
      child: SilText(
        LangOf(context)?.index?.loss_prompt,
        color: ColorUtils.color_subtitle,
        fontSize: 13.sp,
        textAlign: TextAlign.center,
        maxLines: 0,
      ),
    );
  }
}
